/** 站内信SSE消息通讯 */
layui.define(['admin', 'notice'], function (exports) {
    var $ = layui.jquery;
    var admin = layui.admin;
    var notice = layui.notice;
    let source = null;
    let tempData = admin.getTempData("tokenInfo", true);
    let clientId = (tempData && tempData.loginId) ? tempData.loginId : 0;
    if (window.EventSource) {
        // 建立连接
        source = new EventSource('http://localhost:8888/sse/sub?clientId=' + clientId);
        setMessageInnerHTML("start SSE..." + clientId);
        /**
         * 连接一旦建立，就会触发open事件
         * 另一种写法：source.onopen = function (event) {}
         */
        source.onopen = function (ev) {
            setMessageInnerHTML("receiving...");
        }
        /**
         * 客户端收到服务器发来的数据
         * 另一种写法：source.onmessage = function (event) {}
         */
        source.onmessage = function (ev) {
            setMessageInnerHTML(ev.data);
            // console.log(typeof ev.data)
            let d = JSON.parse(ev.data);
            if (typeof d !== 'string') {
                notice.info({
                    timeout: d.timeout,
                    title: d.title,
                    className: 'notice_' + d.id,
                    close: false,
                    position: d.position,
                    message: d.message,
                    onOpened: function () {
                        numIncrement();
                    },
                    buttons: [['<button>收到</button>', function () {
                        notice.hide({}, document.querySelector('.notice_' + d.id));
                        numDecrement();
                        setRead(d.id)
                    }]]
                })
            }
        }

    } else {
        setMessageInnerHTML("Your browser does not support SSE");
    }

    function setRead(messageId) {
        admin.req('/sys/message/read', {userId: clientId, messageId: messageId})
    }

    function setMessageInnerHTML(innerHTML) {
        // document.getElementById('message').innerHTML += innerHTML + '<br/>';
        // console.log(innerHTML);
        let data = admin.getTempData('notice', true);
        console.log(data)
    }

    function numIncrement() {
        let data = admin.getTempData('notice', true);
        if (data) {
            data.num++;
        } else {
            let tnum = 0;
            tnum++;
            data = {num: tnum}
        }
        if (data.num > 0) {
            $('#messageElem').removeClass('layui-hide');
        }
        admin.putTempData('notice', data, true);
    }

    function numDecrement() {
        let data = admin.getTempData('notice', true);
        if (data) {
            data.num--;
            if (data.num === 0) {
                $('#messageElem').addClass('layui-hide');
            }
            admin.putTempData('notice', data, true);
        }
    }

    exports('sse')
})


